<?php
namespace App\Service\Front;

use Illuminate\Support\Facades\DB;

class UserService extends BaseService
{
    //用户

    //一个
    public function getOne($id)
    {
        $res = (array) $this->dbConn($this->dbAdmin)->where('id', $id)->first();
        if (!count($res)) {
            return array('code' => -2, 'msg' => '没有记录');
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $res);
    }

    //注册
    public function doRegist($uname, $upwd)
    {
        $res = (array) $this->dbConn($this->dbUser)->where('uname', $uname)->first();
        if (!empty($res)) {
            return $this->toback(-2, '用户已存在');
        }
        $token = toToken();
        $arys = [
            'uname' => $uname,
            'passwd' => $upwd ? md5($upwd) : md5('123456'),
            'token' => $token,
            'addtime' => toDate(),
            'uptime' => toDate(),
        ];
        $lastid = $this->dbConn($this->dbUser)->insertGetId($arys);
        if (!$lastid) {
            return $this->toback(-1, '注册失败');
        }
        $resData = [
            'uid' => $lastid,
            'uname' => $uname,
            'token' => $token,
        ];
        return $this->toback(0, '', $resData);
    }

    //登录
    public function doLogin($uname, $upwd)
    {
        $res = (array) $this->dbConn($this->dbUser)->where('uname', $uname)->first();
        if (empty($res)) {
            return $this->toback(-2, '没有用户');
        }
        if ($res['passwd'] != md5($upwd)) {
            return $this->toback(-2, '密码错误');
        }
        $this->dbConn($this->dbUser)->where('id', $res['id'])->update(['uptime' => toDate()]);
        $resData = [
            'uid' => $res['id'],
            'uname' => $uname,
            'token' => $res['token'],
        ];
        return $this->toback(0, '', $resData);
    }

    /**
     * 保存微信信息
     * @param array $pas
     */
    public function wxByOpenid($uid, $pas)
    {
        $uOne = (array) $this->dbConn($this->dbUser)->where('id', $uid)->first();
        if (empty($uOne)) {
            return $this->toback(-2, '用户错误');
        } else {
            $uData = [
                'openid' => $pas['openid'],
                'wxjson' => json_encode($pas, JSON_UNESCAPED_UNICODE),
                'wxtime' => toDate(),
            ];
            $this->dbConn($this->dbUser)->where('id', $uid)->update($uData);
        }
        return $this->toback();
    }
}